package com.company.service;

import com.company.dao.StudentDao;
import com.company.dao.StudentDaoImpl;
import com.company.domain.Student;
import com.company.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentServiceImpl implements StudentService {
    private StudentDao dao = new StudentDaoImpl();

    @Override
    public ArrayList<Student> findAll() {
        return dao.findAll();
    }

    @Override
    public Student findById(Integer id) {
        return dao.findById(id);
    }

    @Override
    public int insert(Student stu) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dao.insert(stu, con);
    }

    @Override
    public int update(Student stu) {
        return dao.update(stu);
    }

    @Override
    public int delete(Integer id) {
        return dao.delete(id);
    }

    @Override
    public void insertALL(List<Student> stuList) throws SQLException {
        Connection con = JDBCUtils.getConnection();
        try {
            con.setAutoCommit(false);
            for (Student student : stuList) {
                dao.insert(student, con);
            }
            con.commit();
        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(con, null);
        }
    }
}
